<script setup lang="ts">
import { ref } from 'vue'
import { EntityIdInput } from '../base'
import { getWaypointRoutingSet } from '../routing'
import type { FlightPlan } from './types'
import { getAirportFlightPlanInfo } from './fpl-index'

const id = ref<string | null>(null)
const wpt = ref<string | null>(null)
const depApt = ref<string | null>(null)
const arrApt = ref<string | null>(null)

function filter(lst: FlightPlan[]): FlightPlan[] {
  const predicates: ((e: FlightPlan) => boolean)[] = []
  const id_ = id.value?.trim()?.toLowerCase()
  if (id_ && id_.length > 0) {
    predicates.push((e) => e.id.toLowerCase().indexOf(id_) >= 0)
  }
  const depApt_ = depApt.value
  if (depApt_ && depApt_.length > 0) {
    const af = getAirportFlightPlanInfo(depApt_)
    if (!af || af.departure.length === 0) {
      return []
    }
    const fs = new Set<string>()
    for (const f of af.departure) {
      fs.add(f.id)
    }
    predicates.push((e) => fs.has(e.id))
  }
  const arrApt_ = arrApt.value
  if (arrApt_ && arrApt_.length > 0) {
    const af = getAirportFlightPlanInfo(arrApt_)
    if (!af || af.arrival.length === 0) {
      return []
    }
    const fs = new Set<string>()
    for (const f of af.arrival) {
      fs.add(f.id)
    }
    predicates.push((e) => fs.has(e.id))
  }
  const wpt_ = wpt.value
  if (wpt_ && wpt_.length > 0) {
    const rs = getWaypointRoutingSet(wpt_)
    if (!rs || rs.size === 0) {
      return []
    }
    const rs1 = new Set<string>()
    for (const r of rs) {
      rs1.add(r.id)
    }
    predicates.push((e) => rs1.has(e.routing))
  }

  if (predicates.length <= 0) {
    return lst
  }
  return lst.filter((e) => {
    for (const fn of predicates) {
      if (!fn(e)) {
        return false
      }
    }
    return true
  })
}
defineExpose({ filter })
</script>
<template>
  <div>
    <div class="row">
      <div class="txt-box col-6em">id</div>
      <input class="input col-9em" v-model="id" placeholder="模糊匹配" />
      <div class="txt-box col-6em" style="margin-left: 5em">包含航路点</div>
      <EntityIdInput class="col-9em" v-model="wpt" placeholder="精确匹配" type="Waypoint" />
    </div>
    <div class="row" style="margin-top: 0.25em">
      <div class="txt-box col-6em">起飞机场</div>
      <EntityIdInput class="col-9em" v-model="depApt" placeholder="精确匹配" type="Airport" />
      <div class="txt-box col-6em" style="margin-left: 5em">落地机场</div>
      <EntityIdInput class="col-9em" v-model="arrApt" placeholder="精确匹配" type="Airport" />
    </div>
  </div>
</template>
